#pragma once

#include "srect.h"
#include "rgbcontrol.h"
#include "bmppallette.h"
#include "parentpanel.h"
#include "bmpcolorpanel.h"

class BMPPalletteManager : public ParentPanel
{
public:
	/** how many colors the user can select with the mouse */
	static const int NUM_USER_COLORS = 3;
private:
	/** how many RGB components can be modified (3, unless alpha can be modified, then 4) */
	static const int NUM_RGB_COMPONENTS = 3;
	/** image who's pallette is being managed */
	BitMaP * m_bmp;
	/** selected colors used by the pallette (main,off) */
	BMPColorPanel m_colorPanel[NUM_USER_COLORS];
	/** RGB controls to change the value of the current main color (m_color[0]) */
	RGBControl m_rgb[NUM_RGB_COMPONENTS];
	/** list of colors that the user can select from */
	BMPPallette m_pallette;

	int m_buttonHeight;
public:
	static const int COLOR_MAIN = 0;
	static const int COLOR_OFF = 1;
	static const int COLOR_TRANSPARENT = 2;
	int * getSelectedColorIndex(const int & a_index){return m_colorPanel[a_index].getColorIndex();}
	RGB_QUAD * getSelectedColorRGBA(const int & a_index){return m_bmp->getColor(*getSelectedColorIndex(a_index));}
	Uint32 getSelectedColor(const int & a_index, SDL_PixelFormat * f)
	{return m_bmp?RGBQUAD_toSurfaceColor(*getSelectedColorRGBA(a_index), f):0;}
	void setArea(const SRect & a_area)
	{
		setDirty(0);
		ParentPanel::setArea(a_area);
		SRect buttonArea(a_area);
		SPoint down(0,m_buttonHeight);
		buttonArea.setHeight(m_buttonHeight);
		for(int i = 0; i < NUM_USER_COLORS; ++i)
		{
			m_colorPanel[i].setArea(buttonArea);
			buttonArea.move(down);
		}
		for(int i = 0; i < NUM_RGB_COMPONENTS; ++i)
		{
			m_rgb[i].setArea(buttonArea);
			buttonArea.move(down);
		}
		SRect palletteFrame(buttonArea);
		palletteFrame.setMaxY(a_area.getMaxY());
		m_pallette.setArea(palletteFrame);
		setDirty(0);
	}
	void setBMP(BitMaP * a_bmp)
	{
		m_bmp = a_bmp;
		m_pallette.set(this, a_bmp, m_buttonHeight);
		for(int i = 0; i < NUM_RGB_COMPONENTS; ++i)
		{
			m_colorPanel[i].set(&m_bmp, 0);
		}
		for(int i = 0; i < NUM_RGB_COMPONENTS; ++i)
		{
			m_rgb[i].setRGBControl(getSelectedColorIndex(0), i, m_bmp);
		}
		setDirty(0);
	}
	void refresh()
	{
		for(int i = 0; i < NUM_RGB_COMPONENTS; ++i)
		{
			m_rgb[i].refresh();
		}
		setDirty(0);
	}
	void countColors()
	{
		m_pallette.countColors();
	}
	BMPPalletteManager():m_bmp(0)
	{
		for(int i = 0; i < NUM_RGB_COMPONENTS; ++i)
			addChild(&m_colorPanel[i]);
		for(int i = 0; i < NUM_RGB_COMPONENTS; ++i)
			addChild(&m_rgb[i]);
		addChild(&m_pallette);
		// TODO 16 is a magic number...
		m_buttonHeight = 16;
	}
};